package my.learnDB.tools.resultHandler.impl;


import my.learnDB.tools.resultHandler.ResultListHandlerAbs;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class ResultListHandlerImpl<T> extends ResultListHandlerAbs<T> {

    private Class<T> domainClass;


    public ResultListHandlerImpl(Class<T> domainClass) {
        this.domainClass = domainClass;
    }

    @Override
    public List<T> listHandle(ResultSet rs) {


        try {
            List<T> list = new ArrayList<T>();

            while(rs.next()){

                T bean = domainClass.getDeclaredConstructor().newInstance();

                // resultSet 几个字段
                ResultSetMetaData resultSetMetaData = rs.getMetaData();

                int columnCount = resultSetMetaData.getColumnCount();

                for(int i=1;i<=columnCount;i++){

                    String columnName = resultSetMetaData.getColumnName(i);

                    PropertyDescriptor pd = new PropertyDescriptor(columnName,domainClass);  // 实体类中定义的私有类成员和它的get以及set方法

                    Method method = pd.getWriteMethod();

                    Object columnValue = rs.getObject(columnName);

                    method.invoke(bean,columnValue);
                }
                // 把封装好的对象加入到集合中
                list.add(bean);
            }
            //4.返回
            return list;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
